const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');

// 验证JWT中间件
const authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    return res.status(401).json({ error: '未授权访问' });
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.userId = decoded.userId;
    next();
  } catch (error) {
    return res.status(403).json({ error: '无效的令牌' });
  }
};

// 获取最新文章列表（公开）
router.get('/', (req, res) => {
  try {
    const limit = req.query.limit ? parseInt(req.query.limit) : 3;
    const offset = req.query.offset ? parseInt(req.query.offset) : 0;
    
    // 首先获取置顶文章
    const pinnedArticles = [];
    const pinnedResults = global.db.exec(`
      SELECT id, title, substr(content, 1, 200) as summary, created_at, updated_at, is_pinned 
      FROM articles 
      WHERE status = 'published' AND is_pinned = 1
      ORDER BY updated_at DESC
    `);
    
    if (pinnedResults.length > 0) {
      const { columns, values } = pinnedResults[0];
      for (const row of values) {
        const article = {};
        columns.forEach((col, i) => {
          article[col] = row[i];
        });
        // 添加摘要
        article.summary = article.summary + '...';
        pinnedArticles.push(article);
      }
    }
    
    // 然后获取非置顶的普通文章
    const regularArticles = [];
    const regularResults = global.db.exec(`
      SELECT id, title, substr(content, 1, 200) as summary, created_at, updated_at, is_pinned 
      FROM articles 
      WHERE status = 'published' AND is_pinned = 0
      ORDER BY updated_at DESC
      LIMIT ${limit} OFFSET ${offset}
    `);
    
    if (regularResults.length > 0) {
      const { columns, values } = regularResults[0];
      for (const row of values) {
        const article = {};
        columns.forEach((col, i) => {
          article[col] = row[i];
        });
        // 添加摘要
        article.summary = article.summary + '...';
        regularArticles.push(article);
      }
    }
    
    // 合并置顶和普通文章
    const articles = [...pinnedArticles, ...regularArticles];
    
    // 获取文章总数（用于分页）
    const countResult = global.db.exec(`
      SELECT COUNT(*) FROM articles WHERE status = 'published'
    `);
    
    const totalCount = countResult.length > 0 ? countResult[0].values[0][0] : 0;
    
    res.json({
      articles,
      pagination: {
        total: totalCount,
        offset,
        limit
      }
    });
    
  } catch (error) {
    console.error('获取文章列表错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

// 获取单篇文章详情（公开）
router.get('/:id', (req, res) => {
  try {
    const { id } = req.params;
    
    const results = global.db.exec(`
      SELECT * FROM articles 
      WHERE id = ${id} AND status = 'published'
    `);
    
    if (results.length === 0 || results[0].values.length === 0) {
      return res.status(404).json({ error: '文章不存在' });
    }
    
    const { columns, values } = results[0];
    const article = {};
    
    columns.forEach((col, i) => {
      article[col] = values[0][i];
    });
    
    res.json(article);
  } catch (error) {
    console.error('获取文章详情错误:', error);
    res.status(500).json({ error: '服务器错误' });
  }
});

module.exports = router; 